package com.binyouwei.reverse_development

import android.content.Intent
import android.os.Bundle
import android.os.Debug
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.binyouwei.reverse_development.compose.ui.ComposeActivity
import com.binyouwei.reverse_development.java.ui.JavaActivity
import com.binyouwei.reverse_development.kotlin.ui.KotlinActivity
import com.binyouwei.reverse_development.packet_capture.PacketCaptureActivity
import com.binyouwei.reverse_development.utils.MMKVUtils
import com.tencent.mmkv.BuildConfig

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        findViewById<Button>(R.id.bt_java).setOnClickListener {
            startActivity(Intent(this, JavaActivity::class.java))
        }

        findViewById<Button>(R.id.bt_kotlin).setOnClickListener {
            startActivity(Intent(this, KotlinActivity::class.java))
        }

        findViewById<Button>(R.id.bt_compose).setOnClickListener {
            startActivity(Intent(this, ComposeActivity::class.java))
        }

        val dynamicDebug = findViewById<Button>(R.id.bt_dynamic_debugging)
        val isDebug = MMKVUtils.instance!!.decodeBoolean("is_debug")
        setViewText(dynamicDebug, isDebug)
        dynamicDebug.setOnClickListener {
            val is_debug = MMKVUtils.instance!!.decodeBoolean("is_debug")
            MMKVUtils.instance!!.encode("is_debug", !is_debug)
            setViewText(dynamicDebug, !is_debug)
        }

        if (isDebug) {
            checkForDebugger()
        }

        findViewById<Button>(R.id.bt_packet_capture).setOnClickListener {
            startActivity(Intent(this, PacketCaptureActivity::class.java))
        }
    }

    private fun setViewText(dynamicDebug: Button, debug: Boolean) {
        dynamicDebug.text = if (debug) {
            getString(R.string.turn_off_dynamic_debugging)
        } else {
            getString(R.string.enable_dynamic_debugging)
        }
    }

    private fun checkForDebugger() {
        if (isAppInDebugMode()) {
            // 采取相应措施
            Toast.makeText(this, "该应用禁止动态调试", Toast.LENGTH_LONG).show()
            // 可以选择退出应用
            System.exit(0)
        }
    }

    private fun isAppInDebugMode(): Boolean {
        return BuildConfig.DEBUG || Debug.isDebuggerConnected()
    }

}